/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.controller;

import com.minierp.bean.PayBillBean;
import com.minierp.bean.PayBillItemBean;
import com.minierp.bean.UserBean;
import com.minierp.dao.AdjustBillDao;
import com.minierp.dao.BankAccountBalanceDao;
import com.minierp.dao.BankAccountDao;
import com.minierp.dao.CodeRuleDao;
import com.minierp.dao.CooperBillDao;
import com.minierp.dao.DepartmentDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.PayBillDao;
import com.minierp.dao.PayBillItemDao;
import com.minierp.dao.PayModeDao;
import com.minierp.dao.PurchaseBillDao;
import com.minierp.dao.SerialNumberDao;
import com.minierp.err.NotAllowException;
import com.minierp.err.PermissionDennyException;
import com.minierp.helper.EncCommonHelper;
import com.minierp.helper.EncPayBillFormCtrHelper;
import com.minierp.helper.PageHelper;
import com.minierp.model.CodeRule;
import com.minierp.model.CooperBill;
import com.minierp.model.CooperBillExt;
import com.minierp.model.EnterpriseInfo;
import com.minierp.model.Establishment;
import com.minierp.model.PayBill;
import com.minierp.model.PayBillItem;
import com.minierp.model.PurchaseBill;
import com.minierp.model.PurchaseBillExt;
import com.minierp.model.TallySet;
import com.minierp.service.PayBillService;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class PayBillFormCtr extends SimpleFormController {
	private DepartmentDao departmentDao;
	private BankAccountDao bankAccountDao;
	private PayBillItemDao payBillItemDao;
	private PayBillDao payBillDao;
	private AdjustBillDao adjustBillDao;
	private PurchaseBillDao purchaseBillDao;
	private CooperBillDao cooperBillDao;
	private CodeRuleDao codeRuleDao;
	private SerialNumberDao serialNumberDao;
	private BankAccountBalanceDao bankAccountBalanceDao;
	private PayModeDao payModeDao;
	private IdGenerator idGenerator;
	private PayBillService payBillService;
	private DataSource dataSource;

	protected Map referenceData(HttpServletRequest request) throws Exception {
		HashMap refData = new HashMap();
		String id = request.getParameter("id");
		if (id == null) {
			id = "";
		}

		refData.put("id", id);
		String retVal = request.getParameter("ret_val");
		if (retVal == null) {
			retVal = "";
		}

		refData.put("retVal", retVal);
		refData.put("departmentList", this.departmentDao.getList(true));
		List baList = this.bankAccountDao.getList("", "");
		EnterpriseInfo ent = EncCommonHelper.getEnterpriseInfo(request);
		UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
		long dfTsId = 0L;
		long specId = 0L;
		if (id != null && !id.equals("")) {
			PayBill bb = (PayBill) this.payBillDao.get(PayBill.class,
					Long.parseLong(id));
			specId = bb.getBankAccountId();
			dfTsId = bb.getTallySetId();
		} else {
			dfTsId = ub.getUser().getDfTsId();
		}

		refData.put("bankAccountList",
				PageHelper.parseBaList(baList, ent, ub, dfTsId, specId));
		return refData;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String id = request.getParameter("id");
		CodeRule cr = this.codeRuleDao.get("PAY_BILL");
		if (cr == null) {
			throw new Exception("Code rule not found for pay bill");
		} else {
			PayBillBean form;
			if (id != null && !id.equals("")) {
				PayBill arg18 = (PayBill) this.payBillDao.get(PayBill.class,
						Long.parseLong(id));
				if (arg18 == null) {
					throw new Exception("Record not found for id:" + id);
				}

				Establishment arg21 = (Establishment) this.payBillDao.get(
						Establishment.class, arg18.getReceiverId());
				List arg19 = this.payBillItemDao
						.getListByPayBill(arg18.getId());
				TallySet arg20 = (TallySet) this.payBillDao.get(TallySet.class,
						arg18.getTallySetId());
				form = EncPayBillFormCtrHelper.doFormBackingObjectEdit(cr,
						arg18, arg21, arg20, arg19);
			} else {
				if (!EncCommonHelper.checkPrivilege(request, "PAY_BILL")) {
					throw new PermissionDennyException("Permission Denny");
				}

				String dataType = request.getParameter("data_type");
				String payType = request.getParameter("pay_type");
				UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
				long tallySetId = ub.getUser().getDfTsId();
				Object itemList = new ArrayList();
				Establishment est = null;
				if (dataType != null) {
					String estId;
					String[] startDateStr;
					long endDateStr;
					int endDate;
					if (dataType.equals("COOPER")) {
						estId = request.getParameter("bill_id_str");
						startDateStr = estId.split(";");
						endDateStr = 0L;

						for (endDate = 0; endDate < startDateStr.length; ++endDate) {
							CooperBill arg27 = (CooperBill) this.cooperBillDao
									.get(CooperBill.class, Long
											.parseLong(startDateStr[endDate]));
							CooperBillExt arg26 = (CooperBillExt) this.cooperBillDao
									.get(CooperBillExt.class, Long
											.parseLong(startDateStr[endDate]));
							if (arg27 != null) {
								endDateStr = arg27.getCooperatorId();
								((List) itemList).add(this.parseItemByCoo(
										arg27, arg26));
							}
						}

						if (endDateStr != 0L) {
							est = (Establishment) this.payBillDao.get(
									Establishment.class, endDateStr);
						}

						payType = "COOPER";
					} else if (!dataType.equals("PURCHASE")) {
						Date startDate;
						String arg22;
						String arg23;
						Date arg24;
						SimpleDateFormat arg25;
						if (dataType.equals("COOPERATOR")) {
							estId = request.getParameter("est_id");
							arg22 = request.getParameter("start_date");
							arg23 = request.getParameter("end_date");
							startDate = null;
							arg24 = null;
							arg25 = new SimpleDateFormat("yyyy-MM-dd");
							if (arg22 != null && !arg22.equals("")) {
								startDate = arg25.parse(arg22);
							}

							if (arg23 != null && !arg23.equals("")) {
								arg24 = arg25.parse(EncCommonHelper
										.getNextDateStr(arg23, "yyyy-MM-dd"));
							}

							est = (Establishment) this.payBillDao.get(
									Establishment.class, Long.parseLong(estId));
							itemList = this.parseItems(this.cooperBillDao
									.getListForPay(Long.parseLong(estId),
											tallySetId, startDate, arg24),
									"COOPER_BILL");
							payType = "COOPER";
						} else if (dataType.equals("PROVIDER")) {
							estId = request.getParameter("est_id");
							arg22 = request.getParameter("start_date");
							arg23 = request.getParameter("end_date");
							startDate = null;
							arg24 = null;
							arg25 = new SimpleDateFormat("yyyy-MM-dd");
							if (arg22 != null && !arg22.equals("")) {
								startDate = arg25.parse(arg22);
							}

							if (arg23 != null && !arg23.equals("")) {
								arg24 = arg25.parse(EncCommonHelper
										.getNextDateStr(arg23, "yyyy-MM-dd"));
							}

							est = (Establishment) this.payBillDao.get(
									Establishment.class, Long.parseLong(estId));
							itemList = this.parseItems(this.purchaseBillDao
									.getListForPay(Long.parseLong(estId), "",
											tallySetId, startDate, arg24),
									"PURCHASE_BILL");
							payType = "PURCHASE";
						} else if (dataType.equals("COO_ACCOUNT")) {
							estId = request.getParameter("cooperator_id");
							arg22 = request.getParameter("start_date");
							arg23 = request.getParameter("end_date");
							startDate = null;
							arg24 = null;
							arg25 = new SimpleDateFormat("yyyy-MM-dd");
							if (arg22 != null && !arg22.equals("")) {
								startDate = arg25.parse(arg22);
							}

							if (arg23 != null && !arg23.equals("")) {
								arg24 = arg25.parse(EncCommonHelper
										.getNextDateStr(arg23, "yyyy-MM-dd"));
							}

							itemList = this.parseItems(this.cooperBillDao
									.getListForAccountPay(
											Long.parseLong(estId), startDate,
											arg24, tallySetId), "COOPER_BILL");
							est = (Establishment) this.payBillDao.get(
									Establishment.class, Long.parseLong(estId));
							payType = "COOPER";
						} else if (dataType.equals("PUR_ACCOUNT")) {
							estId = request.getParameter("provider_id");
							arg22 = request.getParameter("start_date");
							arg23 = request.getParameter("end_date");
							startDate = null;
							arg24 = null;
							arg25 = new SimpleDateFormat("yyyy-MM-dd");
							if (arg22 != null && !arg22.equals("")) {
								startDate = arg25.parse(arg22);
							}

							if (arg23 != null && !arg23.equals("")) {
								arg24 = arg25.parse(EncCommonHelper
										.getNextDateStr(arg23, "yyyy-MM-dd"));
							}

							itemList = this
									.parseItems(this.purchaseBillDao
											.getListForAccountPay(
													Long.parseLong(estId),
													startDate, arg24,
													tallySetId),
											"PURCHASE_BILL");
							est = (Establishment) this.payBillDao.get(
									Establishment.class, Long.parseLong(estId));
							payType = "PURCHASE";
						}
					} else {
						estId = request.getParameter("bill_id_str");
						startDateStr = estId.split(";");
						endDateStr = 0L;

						for (endDate = 0; endDate < startDateStr.length; ++endDate) {
							PurchaseBill sf = (PurchaseBill) this.purchaseBillDao
									.get(PurchaseBill.class, Long
											.parseLong(startDateStr[endDate]));
							PurchaseBillExt be = (PurchaseBillExt) this.purchaseBillDao
									.get(PurchaseBillExt.class, Long
											.parseLong(startDateStr[endDate]));
							if (sf != null) {
								endDateStr = sf.getProviderId();
								((List) itemList).add(this.parseItemByPur(sf,
										be));
							}
						}

						if (endDateStr != 0L) {
							est = (Establishment) this.payBillDao.get(
									Establishment.class, endDateStr);
						}

						payType = "PURCHASE";
					}
				}

				form = EncPayBillFormCtrHelper.doFormBackingObjectNew(request,
						payType, cr, est, (List) itemList);
			}

			return form;
		}
	}

	private List<PayBillItemBean> parseItems(List<?> billList, String billType)
			throws Exception {
		ArrayList arr = new ArrayList();
		if (billList != null) {
			for (int i = 0; i < billList.size(); ++i) {
				Object[] bo;
				if (billType.equals("PURCHASE_BILL")) {
					bo = (Object[]) billList.get(i);
					arr.add(this.parseItemByPur((PurchaseBill) bo[0],
							(PurchaseBillExt) bo[1]));
				} else {
					if (!billType.equals("COOPER_BILL")) {
						throw new Exception("pay type not support yet.");
					}

					bo = (Object[]) billList.get(i);
					arr.add(this.parseItemByCoo((CooperBill) bo[0],
							(CooperBillExt) bo[1]));
				}
			}
		}

		return arr;
	}

	private PayBillItemBean parseItemByPur(PurchaseBill b, PurchaseBillExt be) {
		PayBillItemBean cb = new PayBillItemBean();
		PayBillItem c = new PayBillItem();
		c.setPurchaseBillCode(b.getBillCode());
		c.setContent(b.getContent());
		c.setPurchaseBillId(b.getId());
		c.setPurchaseDate(b.getPurchaseDate());
		c.setRemainCost(b.getCost().add(be.getAdjustCost())
				.subtract(be.getPaiedCost()));
		c.setTotalCost(b.getCost());
		if (b.getBillType().equals("BACK")) {
			c.setTotalCost((new BigDecimal(0)).subtract(c.getTotalCost()));
			c.setRemainCost((new BigDecimal(0)).subtract(c.getRemainCost()));
		}

		c.setThisCost(c.getRemainCost());
		cb.setPayBillItem(c);
		cb.setThisCostStr(EncCommonHelper.parseBigDecimal(c.getThisCost()));
		cb.setStatus("NEW");
		return cb;
	}

	private PayBillItemBean parseItemByCoo(CooperBill b, CooperBillExt be) {
		PayBillItemBean cb = new PayBillItemBean();
		PayBillItem c = new PayBillItem();
		c.setPurchaseBillCode(b.getBillCode());
		c.setContent(b.getContent());
		c.setPurchaseBillId(b.getId());
		c.setPurchaseDate(b.getCooperDate());
		c.setRemainCost(b.getCost().add(be.getAdjustCost())
				.subtract(be.getPaiedCost()));
		c.setTotalCost(b.getCost());
		c.setThisCost(c.getRemainCost());
		cb.setPayBillItem(c);
		cb.setThisCostStr(EncCommonHelper.parseBigDecimal(c.getThisCost()));
		cb.setStatus("NEW");
		return cb;
	}

	protected void onBind(HttpServletRequest request, Object command)
			throws Exception {
		PayBillBean form = (PayBillBean) command;
		EncPayBillFormCtrHelper.doOnBind(form, request, this.dataSource);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		ModelAndView mv = new ModelAndView(this.getSuccessView());
		String id = request.getParameter("id");
		String examine = request.getParameter("examine");
		UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
		PayBillBean form = (PayBillBean) command;
		PayBill obj = form.getPayBill();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("attach_file");
		String continueFlag;
		String alertType;
		String printFlag;
		String printDetail;
		if (multipartFile != null && !multipartFile.isEmpty()) {
			continueFlag = multipartFile.getOriginalFilename();
			alertType = EncCommonHelper.getExtendName(continueFlag);
			printFlag = EncCommonHelper.getUploadVirtualPath(this
					.getServletContext());
			printDetail = this.getServletContext().getRealPath(printFlag);
			String fileName = ub.getUser().getId() + "_"
					+ System.currentTimeMillis() + "." + alertType;
			FileCopyUtils.copy(multipartFile.getBytes(), new File(printDetail
					+ System.getProperty("file.separator") + fileName));
			obj.setAttachFile(printFlag + fileName);
		}

		if (examine != null && examine.equals("1")) {
			if (!EncCommonHelper.checkPrivilege(request, "PAY_EXAM")) {
				throw new Exception("Permission deny!");
			}

			obj.setExamined("Y");
			if (ub.getStaffer() != null) {
				obj.setExaminerId(ub.getStaffer().getId());
				obj.setExaminerName(ub.getStaffer().getStafferName());
			}
		} else {
			obj.setExamined("N");
		}

		if (id != null && !id.equals("")) {
			if (!EncCommonHelper.checkPrivilege(request, "PAY_BILL")) {
				throw new Exception("Permission deny!");
			}

			try {
				this.payBillService.txUpdate(form, this.payBillDao,
						this.payBillItemDao, this.idGenerator,
						this.adjustBillDao, this.bankAccountBalanceDao);
			} catch (CannotAcquireLockException arg17) {
				EncCommonHelper.setAlertMessage(request, "事务冲突故障，请重新操作！");
				return this.showForm(request, errors, this.getFormView());
			} catch (NotAllowException arg18) {
				EncCommonHelper.setAlertMessage(request, arg18.getMessage());
				return this.showForm(request, errors, this.getFormView());
			}
		} else {
			try {
				this.payBillService.txInsert(form, this.payBillDao,
						this.payBillItemDao, this.serialNumberDao,
						this.idGenerator, this.adjustBillDao,
						this.bankAccountBalanceDao);
			} catch (CannotAcquireLockException arg19) {
				EncCommonHelper.setAlertMessage(request, "事务冲突故障，请重新操作！");
				return this.showForm(request, errors, this.getFormView());
			} catch (NotAllowException arg20) {
				EncCommonHelper.setAlertMessage(request, arg20.getMessage());
				return this.showForm(request, errors, this.getFormView());
			}
		}

		continueFlag = request.getParameter("continue_flag");
		alertType = request.getParameter("alert_type");
		printFlag = request.getParameter("print_flag");
		printDetail = request.getParameter("print_detail");
		if (continueFlag != null && continueFlag.equals("NEW")) {
			EncCommonHelper.setAlertMessage(request, "付款单保存成功！");
			mv = new ModelAndView(
					"redirect:/finance/PayBillNew.ihtm?ret_val=1&alert_type="
							+ alertType + "&pay_type=" + obj.getPayType());
		} else if (printFlag != null && printFlag.equals("SHOW")) {
			mv = new ModelAndView("redirect:/finance/PayBillPrint.ihtm?id="
					+ obj.getId() + "&print_detail=" + printDetail);
		} else {
			if (alertType == null || !alertType.equals("NONE")) {
				EncCommonHelper.setAlertMessage(request, "付款单保存成功！");
			}

			if (printFlag != null && printFlag.equals("CALLBACK")) {
				mv.addObject("returnValue", String.valueOf(obj.getId()) + ";Y"
						+ ";" + printDetail);
			} else {
				mv.addObject("returnValue", String.valueOf(obj.getId()));
			}
		}

		mv.addObject("alertType", alertType);
		return mv;
	}

	public CodeRuleDao getCodeRuleDao() {
		return this.codeRuleDao;
	}

	public void setCodeRuleDao(CodeRuleDao codeRuleDao) {
		this.codeRuleDao = codeRuleDao;
	}

	public DepartmentDao getDepartmentDao() {
		return this.departmentDao;
	}

	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public IdGenerator getIdGenerator() {
		return this.idGenerator;
	}

	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	public SerialNumberDao getSerialNumberDao() {
		return this.serialNumberDao;
	}

	public void setSerialNumberDao(SerialNumberDao serialNumberDao) {
		this.serialNumberDao = serialNumberDao;
	}

	public BankAccountDao getBankAccountDao() {
		return this.bankAccountDao;
	}

	public void setBankAccountDao(BankAccountDao bankAccountDao) {
		this.bankAccountDao = bankAccountDao;
	}

	public PayBillDao getPayBillDao() {
		return this.payBillDao;
	}

	public void setPayBillDao(PayBillDao payBillDao) {
		this.payBillDao = payBillDao;
	}

	public PayBillItemDao getPayBillItemDao() {
		return this.payBillItemDao;
	}

	public void setPayBillItemDao(PayBillItemDao payBillItemDao) {
		this.payBillItemDao = payBillItemDao;
	}

	public PayBillService getPayBillService() {
		return this.payBillService;
	}

	public void setPayBillService(PayBillService payBillService) {
		this.payBillService = payBillService;
	}

	public AdjustBillDao getAdjustBillDao() {
		return this.adjustBillDao;
	}

	public void setAdjustBillDao(AdjustBillDao adjustBillDao) {
		this.adjustBillDao = adjustBillDao;
	}

	public DataSource getDataSource() {
		return this.dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public BankAccountBalanceDao getBankAccountBalanceDao() {
		return this.bankAccountBalanceDao;
	}

	public void setBankAccountBalanceDao(
			BankAccountBalanceDao bankAccountBalanceDao) {
		this.bankAccountBalanceDao = bankAccountBalanceDao;
	}

	public PayModeDao getPayModeDao() {
		return this.payModeDao;
	}

	public void setPayModeDao(PayModeDao payModeDao) {
		this.payModeDao = payModeDao;
	}

	public PurchaseBillDao getPurchaseBillDao() {
		return this.purchaseBillDao;
	}

	public void setPurchaseBillDao(PurchaseBillDao purchaseBillDao) {
		this.purchaseBillDao = purchaseBillDao;
	}

	public CooperBillDao getCooperBillDao() {
		return this.cooperBillDao;
	}

	public void setCooperBillDao(CooperBillDao cooperBillDao) {
		this.cooperBillDao = cooperBillDao;
	}
}